import React, {useCallback, useEffect, useRef, useState} from 'react';
import {
  PermissionsAndroid,
  Platform,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  BottomSheetFlashList,
  BottomSheetFlatList,
  BottomSheetModal,
  BottomSheetTextInput,
  BottomSheetView,
} from '@gorhom/bottom-sheet';
import {Button, Icon, Search, Text, useAppTheme} from 'tsun-smart-ui';
import {useTranslation} from 'react-i18next';
import CustomBottomSheetBackdrop from './CustomBottomSheetBackdrop';
import {
  Geolocation,
  Position,
  setLocatingWithReGeocode,
  setNeedAddress,
} from 'react-native-amap-geolocation';
import {useDebounceFn} from 'ahooks';
import {AMAP_WEB_KEY} from '@/config/config';

type GeoLocation = {
  longitude: number;
  latitude: number;
  address: string;
};

type AMapSearchResultTips = {
  name: string; /// 名称
  address: string; /// 详细地址
  location: string; /// 经纬度
  district: string; /// 行政区
};

type AMapSearchResult = {
  tips: AMapSearchResultTips[];
};

type SelectAddressBottomSheetProps = {};

const SelectAddressBottomSheet = React.forwardRef<
  BottomSheetModal,
  SelectAddressBottomSheetProps
>((props, ref) => {
  const {t} = useTranslation();
  const appTheme = useAppTheme();
  const [position, setPosition] = useState<GeoLocation>();
  const [keyword, setKeyword] = useState('');
  const [locatingStatus, setLocatingStatus] = useState<
    'locating' | 'success' | 'failed'
  >('locating');
  const abortController = useRef<AbortController>(null);
  const [searchResults, setSearchResults] = useState<AMapSearchResultTips[]>(
    [],
  );

  useEffect(() => {
    if (!position) {
      updateCurrentPosition();
    }
    return () => {
      abortController.current?.abort();
    };
  }, []);

  const updateCurrentPosition = useCallback(async () => {
    if (Platform.OS === 'android') {
      await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
      ]);
    }
    setLocatingWithReGeocode(true);
    setNeedAddress(true);
    Geolocation.getCurrentPosition(
      position => {
        // @ts-ignore
        setPosition(position.location);
        setLocatingStatus('success');
      },
      error => {
        setLocatingStatus('failed');
      },
    );
  }, []);

  const {run: fetchAddressAutoCompletions} = useDebounceFn(
    (keyword: string) => {
      abortController.current?.abort();
      abortController.current = new AbortController();
      if (keyword.length <= 1) {
        setSearchResults([]);
        return;
      }
      const location = !!position
        ? `${position.longitude},${position.latitude}`
        : '';
      fetch(
        `https://restapi.amap.com/v3/assistant/inputtips?keywords=${keyword}&Key=${AMAP_WEB_KEY}&location=${location}`,
        {
          method: 'GET',
          redirect: 'follow',
          signal: abortController.current.signal,
        },
      )
        .then(response => response.json())
        .then(result => {
          const searchResults = result as AMapSearchResult;
          if (searchResults.tips) {
            setSearchResults(searchResults.tips);
          }
        })
        .catch(error => console.log('error', error));
    },
    {wait: 300},
  );

  const renderDefaultContent = useCallback(() => {
    let title: string;
    if (locatingStatus === 'success') {
      title = position?.address || '';
    } else if (locatingStatus === 'locating') {
      title = t('sys.app.locating', {defaultValue: '定位中...'});
    } else {
      title = t('sys.app.locating.failed', {defaultValue: '定位失败'});
    }
    return (
      <View>
        <View className="flex-row justify-between items-center">
          <Text variant="body">
            {t('sys.app.my.location', {defaultValue: '我的位置'})}
          </Text>
          <Button title="检查权限" variant="text" />
        </View>
        <TouchableOpacity
          onPress={() => {
            setLocatingStatus('locating');
          }}>
          <Text>{title}</Text>
        </TouchableOpacity>
      </View>
    );
  }, [locatingStatus, position]);

  /// item的类型应该是tips数组的元素类型
  const renderItem = useCallback(
    ({item, index}: {item: AMapSearchResultTips; index: number}) => {
      const isFirst = index === 0;
      const isLast = index === searchResults.length - 1;
      const borderTopRadius = isFirst ? 8 : 0;
      const borderBottomRadius = isLast ? 8 : 0;
      return (
        <TouchableOpacity
          onPress={() => {
            // ref?.current?.dismiss();
          }}
          className="bg-text6 p-2"
          style={{
            borderTopLeftRadius: borderTopRadius,
            borderTopRightRadius: borderTopRadius,
            borderBottomLeftRadius: borderBottomRadius,
            borderBottomRightRadius: borderBottomRadius,
          }}>
          <Text variant="body">{item.name}</Text>
          <Text variant="caption">{item.address}</Text>
        </TouchableOpacity>
      );
    },
    [searchResults],
  );

  return (
    <BottomSheetModal
      snapPoints={['80%']}
      enableDynamicSizing={false}
      enableBlurKeyboardOnGesture
      enablePanDownToClose
      backdropComponent={CustomBottomSheetBackdrop}
      ref={ref}
      backgroundStyle={{
        backgroundColor: appTheme.colors?.background?.primary,
      }}>
      <BottomSheetView className="flex-1 mx-4 gap-3">
        <View className="bg-text6 flex-row items-center gap-1 h-12 px-3 rounded-full">
          <Icon
            name="search"
            size={22}
            color={appTheme.colors?.neutral?.secondaryTitle}
          />
          <TextInput
            placeholder={t('sys.app.pls.input.address', {
              defaultValue: '请输入地址',
            })}
            className="flex-1 h-8"
            value={keyword}
            onChangeText={text => {
              setKeyword(text);
              fetchAddressAutoCompletions(text);
            }}
          />
        </View>
        <BottomSheetView className="flex-1 overflow-hidden">
          <BottomSheetFlatList
            data={searchResults}
            renderItem={renderItem}
            ListEmptyComponent={renderDefaultContent}
            ItemSeparatorComponent={ItemSeparator}
            keyExtractor={(item, index) => index.toString()}
            // contentContainerClassName={'bg-text6 rounded--[8px] px-3 py-2 overflow-hidden'}
          />
        </BottomSheetView>
      </BottomSheetView>
    </BottomSheetModal>
  );
});

export default SelectAddressBottomSheet;

const ItemSeparator: React.FC = React.memo(() => {
  return (
    <View className="bg-text6 items-stretch">
      <View className={`bg-line1 h-[1px] my-2 mx-1`} />
    </View>
  );
});
